<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      th:replace="~{layout/base :: layout(~{::title}, ~{::section})}">
<head>
    <meta charset="UTF-8">
    <title>上传书籍 - 电子书下载平台</title>
</head>
<body>
    <section>
        <div class="container py-5">
            <div class="row">
                <div class="col-12">
                    <h2 class="mb-4">上传书籍</h2>
                </div>
                
                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-body">
                            <div class="alert alert-success" role="alert" th:if="${uploadSuccess}">
                                <i class="fas fa-check-circle me-2"></i>
                                <span>书籍上传成功！您的上传将在审核通过后显示在平台上。</span>
                            </div>
                            
                            <div class="alert alert-danger" role="alert" th:if="${uploadError}">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                <span th:text="${uploadError}">上传失败，请重试</span>
                            </div>
                            
                            <form th:action="@{/books/upload}" method="post" enctype="multipart/form-data" id="uploadForm">
                                <!-- 上传区域 -->
                                <div class="mb-4">
                                    <label class="form-label">选择文件</label>
                                    <div id="uploadArea" class="upload-area mb-2">
                                        <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                                        <h5 class="mb-2">拖放文件到这里或点击选择</h5>
                                        <p class="text-muted mb-0">支持EPUB、MOBI、PDF格式，最大100MB</p>
                                        <input type="file" id="bookFileInput" name="file" accept=".epub,.mobi,.pdf" style="display: none;" required>
                                    </div>
                                    <div id="fileInfo" class="d-flex align-items-center" style="display: none !important;">
                                        <i class="fas fa-file-alt text-primary me-2"></i>
                                        <span id="selectedFileName">未选择文件</span>
                                        <button type="button" class="btn btn-sm btn-link text-danger ms-auto" id="removeFile">
                                            <i class="fas fa-times"></i> 移除
                                        </button>
                                    </div>
                                </div>
                                
                                <div id="filePreview" class="mb-4">
                                    <!-- 文件预览区域，由JS填充内容 -->
                                </div>
                                
                                <hr>
                                
                                <!-- 书籍元数据表单 -->
                                <div class="row mb-3">
                                    <div class="col-md-8">
                                        <label for="title" class="form-label">书名 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="title" name="title" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label for="language" class="form-label">语言 <span class="text-danger">*</span></label>
                                        <select class="form-select" id="language" name="language" required>
                                            <option value="">选择语言</option>
                                            <option value="简体中文">简体中文</option>
                                            <option value="繁體中文">繁體中文</option>
                                            <option value="English">English</option>
                                            <option value="日本語">日本語</option>
                                            <option value="한국어">한국어</option>
                                            <option value="Français">Français</option>
                                            <option value="Deutsch">Deutsch</option>
                                            <option value="Español">Español</option>
                                            <option value="Русский">Русский</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="author" class="form-label">作者 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="author" name="author" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="translator" class="form-label">译者</label>
                                        <input type="text" class="form-control" id="translator" name="translator">
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="isbn" class="form-label">ISBN</label>
                                        <input type="text" class="form-control" id="isbn" name="isbn" 
                                               pattern="^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$">
                                        <div class="form-text">ISBN-10或ISBN-13格式</div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="publisher" class="form-label">出版社</label>
                                        <input type="text" class="form-control" id="publisher" name="publisher">
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <label for="pubYear" class="form-label">出版年份</label>
                                        <input type="number" class="form-control" id="pubYear" name="pubYear" min="1800" max="2100">
                                    </div>
                                    <div class="col-md-8">
                                        <label for="category" class="form-label">分类 <span class="text-danger">*</span></label>
                                        <select class="form-select" id="category" name="category" required>
                                            <option value="">选择分类</option>
                                            <option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}">分类名称</option>
                                            <!-- 静态示例，当没有数据时显示 -->
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="1">文学</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="2">科技</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="3">教育考试</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="4">经济管理</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="5">计算机</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="6">历史</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="7">哲学宗教</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="8">艺术</option>
                                            <option th:if="${categories == null || #lists.isEmpty(categories)}" value="9">生活</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label">书籍简介</label>
                                    <textarea class="form-control" id="description" name="description" rows="4"></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="coverFile" class="form-label">自定义封面（可选）</label>
                                    <input type="file" class="form-control" id="coverFile" name="coverFile" accept="image/*">
                                    <div class="form-text">如果不上传，系统将尝试从电子书中提取封面</div>
                                </div>
                                
                                <div class="mb-3 form-check">
                                    <input type="checkbox" class="form-check-input" id="agreeTerms" name="agreeTerms" required>
                                    <label class="form-check-label" for="agreeTerms">
                                        我确认拥有此书的上传权利，且上传不侵犯他人著作权
                                    </label>
                                </div>
                                
                                <div class="text-end">
                                    <button type="button" class="btn btn-outline-secondary me-2" id="cancelUpload">取消</button>
                                    <button type="submit" class="btn btn-primary" id="submitUpload">上传书籍</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">上传须知</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <h6><i class="fas fa-check-circle text-success me-2"></i>支持的格式</h6>
                                <p>EPUB、MOBI、PDF（每种格式最大100MB）</p>
                            </div>
                            <div class="mb-3">
                                <h6><i class="fas fa-award text-warning me-2"></i>上传奖励</h6>
                                <p>每成功上传一本书籍，获得5积分奖励</p>
                            </div>
                            <div class="mb-3">
                                <h6><i class="fas fa-history text-info me-2"></i>审核流程</h6>
                                <p>上传后需要管理员审核，通常在1-3个工作日内完成</p>
                            </div>
                            <div>
                                <h6><i class="fas fa-exclamation-triangle text-danger me-2"></i>注意事项</h6>
                                <ul class="ps-3">
                                    <li>请勿上传非法或侵权内容</li>
                                    <li>尽量提供完整准确的书籍信息</li>
                                    <li>同一本书的不同格式可以分别上传</li>
                                    <li>请确保文件可以正常打开</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card mt-4">
                        <div class="card-header">
                            <h5 class="mb-0">我的上传记录</h5>
                        </div>
                        <div class="card-body">
                            <div class="list-group list-group-flush">
                                <!-- 动态数据 -->
                                <a th:each="upload : ${recentUploads}" th:href="@{'/books/' + ${upload.bookId}}"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    <div>
                                        <span th:text="${upload.title}">书名</span>
                                        <span class="badge" th:classappend="${upload.status == '通过' ? 'bg-success' : (upload.status == '拒绝' ? 'bg-danger' : 'bg-warning')}"
                                              th:text="${upload.status}">状态</span>
                                    </div>
                                    <small class="text-muted" th:text="${#temporals.format(upload.uploadTime, 'MM-dd HH:mm')}">01-15 12:30</small>
                                </a>
                                
                                <!-- 静态示例，当没有数据时显示 -->
                                <a th:if="${recentUploads == null || #lists.isEmpty(recentUploads)}" href="/books/1"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    <div>
                                        <span>人工智能导论</span>
                                        <span class="badge bg-success">通过</span>
                                    </div>
                                    <small class="text-muted">01-15 12:30</small>
                                </a>
                                <a th:if="${recentUploads == null || #lists.isEmpty(recentUploads)}" href="/books/2"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    <div>
                                        <span>Python编程：从入门到实践</span>
                                        <span class="badge bg-warning">待审核</span>
                                    </div>
                                    <small class="text-muted">01-14 18:45</small>
                                </a>
                                <a th:if="${recentUploads == null || #lists.isEmpty(recentUploads)}" href="#"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    <div>
                                        <span>数据结构与算法分析</span>
                                        <span class="badge bg-danger">拒绝</span>
                                    </div>
                                    <small class="text-muted">01-10 09:15</small>
                                </a>
                            </div>
                            <div class="mt-3 text-end">
                                <a th:href="@{/user/uploads}" class="btn btn-sm btn-outline-primary">查看全部</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('bookFileInput');
        const fileInfo = document.getElementById('fileInfo');
        const selectedFileName = document.getElementById('selectedFileName');
        const removeFileBtn = document.getElementById('removeFile');
        const filePreview = document.getElementById('filePreview');
        const cancelUploadBtn = document.getElementById('cancelUpload');
        const uploadForm = document.getElementById('uploadForm');
        const coverFileInput = document.getElementById('coverFile');
        const coverPreviewDiv = document.createElement('div');
        coverPreviewDiv.className = 'mt-2';
        
        // 初始化上传区域
        if (uploadArea && fileInput) {
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('border-primary');
            });
            
            uploadArea.addEventListener('dragleave', function() {
                this.classList.remove('border-primary');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('border-primary');
                
                if (e.dataTransfer.files.length) {
                    handleFileSelection(e.dataTransfer.files[0]);
                }
            });
            
            fileInput.addEventListener('change', function() {
                if (this.files.length) {
                    handleFileSelection(this.files[0]);
                }
            });
        }
        
        // 处理文件选择
        function handleFileSelection(file) {
            // 检查文件格式
            const validExtensions = ['.epub', '.mobi', '.pdf'];
            const fileName = file.name.toLowerCase();
            const isValidFile = validExtensions.some(ext => fileName.endsWith(ext));
            
            if (!isValidFile) {
                showToast('不支持的文件格式，请上传EPUB、MOBI或PDF文件', 'error');
                fileInput.value = '';
                return;
            }
            
            // 检查文件大小
            if (file.size > 100 * 1024 * 1024) { // 100MB
                showToast('文件过大，最大支持100MB', 'error');
                fileInput.value = '';
                return;
            }
            
            // 显示文件信息
            selectedFileName.textContent = file.name;
            fileInfo.style.display = 'flex';
            
            // 根据文件类型显示不同图标
            let fileIcon = fileInfo.querySelector('i');
            if (fileName.endsWith('.pdf')) {
                fileIcon.className = 'fas fa-file-pdf text-danger me-2';
            } else if (fileName.endsWith('.epub')) {
                fileIcon.className = 'fas fa-book text-primary me-2';
            } else if (fileName.endsWith('.mobi')) {
                fileIcon.className = 'fas fa-tablet-alt text-success me-2';
            }
            
            // 尝试提取元数据
            filePreview.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i> 正在处理您的文件，提取元数据...</div>';
            
            // 这里只是模拟元数据提取，实际项目中需要发送到后端处理
            setTimeout(function() {
                // 模拟数据，实际应从后端API获取
                const mockData = {
                    title: fileName.split('.')[0],
                    author: '未知作者',
                    coverUrl: '/img/book1.jpg'
                };
                
                // 填充表单
                document.getElementById('title').value = mockData.title;
                document.getElementById('author').value = mockData.author;
                
                // 显示封面预览
                filePreview.innerHTML = `
                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <img src="${mockData.coverUrl}" class="img-thumbnail" alt="封面预览" style="max-height: 200px;">
                                </div>
                                <div class="col-md-8">
                                    <h5>从文件中提取的信息</h5>
                                    <p class="mb-1"><strong>书名:</strong> ${mockData.title}</p>
                                    <p class="mb-1"><strong>作者:</strong> ${mockData.author}</p>
                                    <p class="text-muted small">如有不准确，请在下方表单中修正</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }, 1500);
        }
        
        // 移除文件
        if (removeFileBtn) {
            removeFileBtn.addEventListener('click', function() {
                fileInput.value = '';
                fileInfo.style.display = 'none';
                filePreview.innerHTML = '';
            });
        }
        
        // 取消上传
        if (cancelUploadBtn) {
            cancelUploadBtn.addEventListener('click', function() {
                if (confirm('确定要取消上传吗？已填写的信息将丢失。')) {
                    window.location.href = '/';
                }
            });
        }
        
        // 表单验证
        if (uploadForm) {
            uploadForm.addEventListener('submit', function(event) {
                if (!fileInput.files.length) {
                    event.preventDefault();
                    showToast('请选择要上传的文件', 'error');
                    return;
                }
                
                if (!document.getElementById('agreeTerms').checked) {
                    event.preventDefault();
                    showToast('请确认您拥有上传权利', 'error');
                    return;
                }
                
                // 显示上传中提示
                document.getElementById('submitUpload').disabled = true;
                document.getElementById('submitUpload').innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>上传中...';
            });
        }
        
        // 封面预览
        if (coverFileInput) {
            coverFileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        coverPreviewDiv.innerHTML = `<img src="${e.target.result}" class="img-thumbnail" alt="封面预览" style="max-height: 150px;">`;
                        coverFileInput.parentNode.appendChild(coverPreviewDiv);
                    }
                    reader.readAsDataURL(this.files[0]);
                } else {
                    coverPreviewDiv.innerHTML = '';
                }
            });
        }
        
        // ISBN验证
        const isbnInput = document.getElementById('isbn');
        if (isbnInput) {
            isbnInput.addEventListener('blur', function() {
                if (this.value && !this.checkValidity()) {
                    showToast('请输入有效的ISBN格式', 'warning');
                }
            });
        }
    });
    </script>
</body>
</html> 